// 公用js
var BASE_SERVER_URL = "/maopu/";
var PAGE_NUM = 9; //总页数
//var URL = "http://www.imdcfz.com/maopu";
var URL = "http://localhost:8081/maopu";

/*窗口大小*/

var winWidth, winHeight;

/*触屏应用*/
var nowpageC = 1; //当前页码数
var maxpage = 9; //共计页码数
var prepageC = 1; //上一页页码数
var isAnimation = false; //是否正在动画

/*音乐播放器*/
var playstate = 0; //播放状态 0为不播放 1为播放
var myvideo; //我的播放器
var initState = 0; //0 未初始化，1初始化
/* */
var cityPicker; //所在地区选择器
var province, city, county;
var swipeEnable = true; //当前是否可滑动页面
var swipeBack = false; //当处于首页时，是否可以逆向滑动

var phone = ""; //用户手机号
var cache = false;

/*分享*/

/*浏览器监听*/
function loadComplete() {
	console.log("加载完成");
	document.addEventListener("touchmove", function(event) {
		event.preventDefault();
	}, false);
	$(window).keydown(function(event) {
		choosepage(event.keyCode);
	});
	$(document).swipeUp(function() {
		if(swipeEnable)
			nextpage();
	});
	$(document).swipeDown(function() {
		if(swipeEnable)
			prepage();
	});

	checkWinSize();

	mui.ready(function() {
		initVariables();
		initListeners();
		wxShare();
	});
	
};
window.onresize = function() {
	checkWinSize();
};

/*功能函数*/
function changeVideostate() { //修改播放器播放状态 
	if(myvideo.paused) {
		myvideo.play();
		$("#videoBtImg").addClass("videoBtXuanzhuan");
	} else {
		myvideo.pause();
		$("#videoBtImg").removeClass("videoBtXuanzhuan");
	}

}

function choosepage(keycode) { //选择页码
	if(keycode === 38 || keycode === 20) prepage();
	if(keycode === 40 || keycode === 32) nextpage();
}

function nextpage() { //下一页
	if(isAnimation == false) {
		prepageC = nowpageC;
		if(nowpageC == maxpage) {
			nowpageC = 1;
		} else {
			nowpageC++;
		}
		if(nowpageC == 5 && !mui(".pg5-jp")[0].classList.contains("is-stage-5")) {
			console.log("锁定滑动");
			swipeEnable = false;
		}
			
		if(nowpageC == PAGE_NUM) {
			swipeBack = true;
		}
		gopage("up");
	}
}

function prepage() { //上一页
	if(isAnimation == false) {
		if(nowpageC == 1) {
			//当前处于首页，需要判断 swipeBack 的值
			if(swipeBack) {
				prepageC = nowpageC;
				nowpageC = maxpage;
				gopage("down");
			}

		} else {
			prepageC = nowpageC;
			nowpageC--;
			gopage("down");
		}

	}
}

function gopage(state) { //翻页方法
	var nextpageCss = ".page" + nowpageC;
	var prepageCss = ".page" + prepageC;
	var Outcss, Incss;

	if(state == "up") { //上翻
		Outcss = "page-moveToTopbox";
		Incss = "page-moveFromBottombox";
	} else if(state == "down") { //下翻
		Outcss = "page-moveToBottombox";
		Incss = "page-moveFromTopbox";
	}
	isAnimation = true;
	$(nextpageCss).removeClass("hide");
	$(prepageCss).addClass(Outcss);
	$(nextpageCss).addClass(Incss);

	setTimeout(function() {
		$(prepageCss).removeClass(Outcss);
		$(prepageCss).removeClass("page-current");
		$(prepageCss).addClass("hide");
		$(prepageCss).find("img").addClass("hide");
		$(nextpageCss).addClass('page-current');
		$(nextpageCss).removeClass(Incss);
		$(nextpageCss).find("img").removeClass("hide");
		isAnimation = false;
	}, 600);
}

function checkWinSize() { //检测窗口大小
	getWindowSize();
	document.getElementById('content').style.width = winWidth + "px";
	document.getElementById('content').style.height = winHeight + "px";
	if(winWidth > winHeight) { //横屏
		document.getElementById('tipbox').style.display = "block";
		document.getElementById("loading").style.width = winHeight * 0.6 + "px";
		document.getElementById("loading").style.height = winHeight * 0.6 + "px";
		//top=(页面高度-盒子高度)/2
		document.getElementById("loading").style.top = (winHeight - winHeight * 0.6) / 2 + "px";
		//left=(页面宽度-盒子宽度)/2
		document.getElementById("loading").style.left = (winWidth - winHeight * 0.6) / 2 + "px";
		//停止播放，并且不显示播放器按钮
		if(initState == 1) {
			myvideo.paused();
			$("#videoBtImg").removeClass("videoBtXuanzhuan");
		}
	} else {
		document.getElementById('tipbox').style.display = "none";
		document.getElementById("loading").style.width = winWidth * 0.6 + "px";
		document.getElementById("loading").style.height = winWidth * 0.6 + "px";
		//top=(页面高度-盒子高度)/2
		document.getElementById("loading").style.top = (winHeight - winWidth * 0.6) / 2 + "px";
		//left=(页面宽度-盒子宽度)/2
		document.getElementById("loading").style.left = (winWidth - winWidth * 0.6) / 2 + "px";
		loading();
		//显示播放器并播放
		if(initState == 0) { //初始化播放器
			document.getElementById('videoContainer').innerHTML = '<audio autoplay="autoplay" loop="loop" id="myVideobox"><source src="http://od2cooi8a.bkt.clouddn.com/maopu/music/bgsound.mp3"></audio>';
			myvideo = document.getElementById('myVideobox');
			myvideo.play();
			$("#videoBtImg").addClass("videoBtXuanzhuan");
		} else { //播放操作
			myvideo.play();
			$("#videoBtImg").addClass("videoBtXuanzhuan");
		}
	}

}

function loading() { //载入第一页
	if(document.readyState == "complete") {
		setTimeout(function() {
			$(".loading").hide();
			$(".content").show();
		}, 2000);
		
	}
}
//获取窗口大小
function getWindowSize() {
	//获取窗口宽度
	if(window.innerWidth) {
		winWidth = window.innerWidth;
	} else if((document.body) && (document.body.clientWidth)) {
		winWidth = document.body.clientWidth;
	}
	//获取窗口高度
	if(window.innerHeight) {
		winHeight = window.innerHeight;
	} else if((document.body) && (document.body.clientHeight)) {
		winHeight = document.body.clientHeight;
	}
	//通过深入Document内部对body进行检测，获取窗口大小
	if(document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
		winHeight = document.documentElement.clientHeight;
		winWidth = document.documentElement.clientWidth;
	}
}

/**
 * ajax网络请求
 */
function ajax(action, params, cbSuccess, cbError, auto) {
	url = BASE_SERVER_URL + action;
	console.log(new Date().toString());
	console.log("action地址为：" + url);
	if(typeof(auto) == "undefined") {
		auto = true;
	}
	console.log("参数为：" + JSON.stringify(params));
	mui.ajax(url, {
		data: params,
		type: 'post',
		timeout: 20000,
		success: function(data) {
			console.log("服务端返回的数据为：" + data);
			if(data) {
				if(auto) {
					data = eval("(" + data + ")");
				}
			}
			cbSuccess(data);
		},
		error: function(xhr, type, errorThrown) {
			console.log("发生异常，类型为：" + type);
			if(type == "timeout") {
				mui.toast("请求超时");
			} else if(type == "error") {
				console.log(xhr.toString());
			} else {
				console.log(xhr.toString());
			}
			cbError();
		}
	});
}

/**
 * 检查手机号格式
 * @param {Object} phone
 */
function isMobilePhone(phone) {
	//	console.log("phone=" + phone);
	var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(1S[0-9]{1}))+\d{8})$/;
	return myreg.test(phone);
}

function initVariables() {	
	cityPicker = new mui.PopPicker({
		layer: 3
	});
	cityPicker.setData(cityData3);
}

/**
 * 添加事件监听
 */
function initListeners() {
	//地址栏添加点击监听
	mui("#address")[0].addEventListener('click', function(event) {
		console.log("点击地址栏");
		swipeEnable = false;
		cityPicker.show(function(items) {
			province = items[0].text;
			city = items[1].text;
			county = items[2].text;
			console.log(province + "-" + city + "-" + county);
			mui("#lb-address")[0].innerText = province + " " + city + " " + county;
			province = items[0].value;
			city = items[1].value;
			county = items[2].value;
			console.log(province + "-" + city + "-" + county);
			swipeEnable = true;
		});
	}, false);

	//获取验证码监听
	mui("#btn-send-code")[0].addEventListener('click', function(event) {
		console.log("获取验证码");
		var phone = mui("#ip-phone")[0].value.toString();
		if(phone.length == 0) {
			mui.toast("请输入手机号");
			return;
		}
		if(!isMobilePhone(phone)) {
			mui.toast("手机号格式不正确");
			return;
		}
		//发送到服务器
		requestCode(phone);

	}, false);

	//提交按钮添加监听
	mui("#submit")[0].addEventListener('click', function(event) {
		console.log("点击提交按钮");
		var name = mui("#ip-name")[0].value.toString().trim();
		console.log("name=" + name);
		if(name.length == 0) {
			mui.toast("请输入姓名");
			return;
		}
		phone = mui("#ip-phone")[0].value.toString();
		console.log("phone=" + phone);
		if(phone.length == 0) {
			mui.toast("请输入手机号");
			return;
		}
		if(!isMobilePhone(phone)) {
			mui.toast("手机号格式不正确");
			return;
		}
		var code = mui("#ip-code")[0].value.toString();
		console.log("code=" + code);
		if(code.length == 0) {
			mui.toast("请输入验证码");
			return;
		}
		var address = mui("#lb-address")[0].innerText;
		console.log("address=" + address);
		if(address.length == 0) {
			mui.toast("请选择地址");
			return;
		}
		//向服务器提交请求
		submit(name, phone, code, address);
	});

	//抽奖监听
	mui("#turntable-btn")[0].addEventListener('click', function(event) {
		console.log("点击抽奖");
		if(phone != "" && phone != null && phone != undefined) {
			//检查是否已到十点,十点之前不允许抽奖
			var currDate = new Date();//获取当前时间
			var currHour = currDate.getHours();//获取当前小时
			console.log("当前小时数为："+currHour);
			if(currHour < 10)
				mui.toast("请10:00之后再来哦！");
			else{
				//出现等待提示
				mui("#waiting-toast")[0].style.display = "block";
				draw(phone);
			}
			
		} else {
			mui.toast("请先报名哦");
		}

	});
}

/**
 * 抽奖
 * @param {Object} phone 用户手机号
 */
function draw(phone) {
	ajax("draw", {
			phone: phone
		},
		function(data) {
			mui("#waiting-toast")[0].style.display = "none";
			if(data.hasOwnProperty("code")) {
				if(data.code == 0) {
					console.log("用户可以抽奖，肯定能抽中，转动转盘");
					// 用户可以抽奖，肯定能抽中，转动转盘
					window.turntable(true, function() {
						//通知服务器
						console.log("通知服务器");
						notifyServerDraw(phone, data.code);
					});
				} else if(data.code == 1 || data.code == 2) {
					console.log("用户可以抽奖，但抽不中，转动转盘");
					//用户可以抽奖，但抽不中，转动转盘
					window.turntable(false, function() {
						//通知服务器
						console.log("通知服务器");
						notifyServerDraw(phone, data.code);
					});
				} else if(data.code == 3) {
					//今天已抽过奖
					console.log("今天已抽过奖");
					mui.toast("今天已抽过奖，请明天再来");
				} else if(data.code == 4) {
					//该用户已抽中过奖
					console.log("该用户已抽中过奖");
					//出现提示，不要太贪心
					mui(".pg8-6")[1].style.display = "block";
					//设置点击监听
					mui(".pg8-6")[1].addEventListener("click", function(event) {
						this.style.display = 'none';
					});
				}
			} else
				mui.toast("提交失败，请稍后重试");
		},
		function() {
			mui("#waiting-toast")[0].style.display = "none";
		}
	);
}

/**
 * 通知服务器中奖
 * @param {Object} phone
 * @param {Object} code 0-中奖 1-谢谢参与，明天再来 2-谢谢参与
 */
function notifyServerDraw(phone, code) {
	ajax("drawOver", {
			phone: phone,
			code: code
		},
		function(data) {
			if(data.hasOwnProperty("code") && data.code == 0) {
				console.log("提交服务器成功");
				//提交服务器成功
				if(code == 0) {
					//出现提示，恭喜用户中奖
					mui.toast("恭喜抽中奖");
					mui(".pg8-5")[0].style.display = "block";
					//设置点击监听
					mui(".pg8-5")[0].addEventListener("click", function(event) {
						this.style.display = 'none';
					});
				} else if(code == 1) {
					//出现提示，谢谢参与，明天再来					
					mui(".pg8-6")[0].style.display = "block";
					//设置点击监听
					mui(".pg8-6")[0].addEventListener("click", function(event) {
						this.style.display = 'none';
						//调用微信分享接口
						//wxShare();				
						//出现遮罩
						var mask = mui.createMask(function(){
							mui(".pg8-7")[0].style.display = 'none';
						});
						mask.show();
						//出现分享图片
						mui(".pg8-7")[0].style.display = "block";
						//设置点击监听
						mui(".pg8-7")[0].addEventListener("click", function(event) {
							this.style.display = 'none';
							mask.close();
						});
					});
				} else if(code == 2) {
					//TODO 出现提示，谢谢参与
					mui.toast("谢谢参与");
				}

			} else {
				mui.toast("抽奖失败，请稍后重试");
			}
		},
		function() {
			mui.toast("抽奖失败，请稍后重试");			
		}
	);
}

/**
 * 微信分享配置
 */
function wxShare() {
	ajax("wx/config", {
			url: location.href ? location.href.split('#')[0] : ''
		},
		function(data) {
			if(data.code == 0 && data.body) {
				var dataBody = data.body;
				wx.config({
					debug: false,
					appId: dataBody.appId,
					timestamp: dataBody.timestamp,
					nonceStr: dataBody.nonceStr,
					signature: dataBody.signature,
					jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
				});
			} else {
				//提示，分享失败
				mui.toast("分享失败");
			}

		},
		function() {
			mui.toast("分享失败");
		});
}

/**
 * 向服务器请求验证码
 * @param {Object} phone
 */
function requestCode(phone) {
	//按钮设为不可点击
	mui("#btn-send-code")[0].disabled = true;
	ajax("requestCode", {
			phone: phone
		},
		function(data) {
			if(data.code == 0) {
				mui.toast("验证码发送成功");
				//开始60秒倒计时
				countDown(60);
			} else {
				mui.toast(data.hasOwnProperty("msg") ? data.msg : "验证码请求失败");
				//按钮设为不可点击
				mui("#btn-send-code")[0].disabled = false;
			}
		},
		function() {
			mui.toast("验证码请求失败");
			mui("#btn-send-code")[0].disabled = false;
		}
	);
}

/**
 * 提交给服务器
 * @param {Object} name 用户姓名
 * @param {Object} phone 
 * @param {Object} code
 * @param {Object} address
 */
function submit(name, phone, code, address) {
	var params = {
		name: name,
		phone: phone,
		code: code,
		address: address,
		province: province,
		city: city,
		county: county
	};
	ajax("register", params,
		function(data) {
			if(data.hasOwnProperty("code") && data.code == 0) {
				mui.toast("报名成功，请前往抽奖");
				//转到抽奖页面
				setTimeout(nextpage(), 2000);
			} else if(data.hasOwnProperty("code") && data.code == 1) {
				mui.toast("您已经注册过，请前往抽奖");
				//转到抽奖页面
				setTimeout(nextpage(), 2000);
			} else if(data.hasOwnProperty("code") && data.code == -1) {
				mui.toast("验证码错误");
			} else
				mui.toast("提交失败，请稍后重试");

		},
		function() {
			mui.toast("提交失败，请稍后重试");
		}
	);
}

/**
 * 倒计时
 * @param {Object} seconds
 */
function countDown(seconds) {
	mui("#btn-send-code")[0].value = seconds + "s后重新获取";
	var count = parseInt(seconds);
	if(count >= 0) {
		count--;
		setTimeout("countDown(" + count + ")", 1000);
	} else {
		mui("#btn-send-code")[0].value = "点击获取验证码";
		//按钮设为可点击
		mui("#btn-send-code")[0].disabled = false;
	}
}

/**
 * 微信分享
 */
wx.ready(function() {

	wx.onMenuShareTimeline({

		title: '毛铺发现不一样的山东',

		desc: '毛铺发现不一样的山东',

		link: 'http://ruddcc.com',

		imgUrl: 'images/wx_fx.jpg',

		cancel: function() {

			mui.toast("取消分享");

		},

		fail: function() {
			mui.toast("分享失败");
		},

		trigger: function() {

		}

	});

	wx.onMenuShareAppMessage({

		title: '毛铺发现不一样的山东',

		desc: '毛铺发现不一样的山东',

		link: 'http://ruddcc.com',

		imgUrl: 'http://m.ruddcc.com/maopu/images/wx_fx.jpg',

		cancel: function() {
			mui.toast("取消分享");
		},

		fail: function() {
			mui.toast("分享失败");
		},

		trigger: function() {

			//$('#share-wrapper').hide();

		}

	});

	console.log("微信配置成功");	

});
